from 第18天.utils.http_request import HttpRequest


def retry_token(func):
    def wrapper(self, *args, **kwargs):
        _result = func(self, *args, **kwargs)
        if _result.get("errcode") == 42001:
            self.init_access_token()
            _result = func(self, *args, **kwargs)
        return _result
    return wrapper


class WechatRequest(HttpRequest):
    CORP_ID = "ww183fe17a0f308505"
    CORP_SECRET = "uldHoRf7KmFs-fNloZ8hB40fgXQR1B8FZwn9UM3gArk"

    ACCESS_TOKEN = None

    def __init__(self):
        super().__init__("qyapi.weixin.qq.com")
        self.init_access_token()

    def init_access_token(self):
        if WechatRequest.ACCESS_TOKEN is None:
            _result = super().get("/cgi-bin/gettoken", {
                "corpid": WechatRequest.CORP_ID,
                "corpsecret": WechatRequest.CORP_SECRET
            })
            WechatRequest.ACCESS_TOKEN = _result.get("access_token")

    def _assert_result(self, result_json):
        if result_json.get("errcode") != 0 or result_json.get("errmsg") != "ok":
            raise Exception(f"查询接口调用失败: {result_json}")

    def _assert_create_result(self, result_json):
        if result_json.get("errcode") != 0 or result_json.get("errmsg") != "created":
            raise Exception(f"创建接口调用失败: {result_json}")

    def get(self, api: str, params: dict = None):
        if params is None:
            params = {}
        params["access_token"] = WechatRequest.ACCESS_TOKEN
        return super().get(api, params)

    def post(self, api: str, body: dict, params: dict = None):
        if params is None:
            params = {}
        params["access_token"] = WechatRequest.ACCESS_TOKEN
        return super().post(api, body, params)


if __name__ == "__main__":
    wechat_request = WechatRequest()
    result = wechat_request.post("/cgi-bin/user/getuserid", {
       "mobile": "18069890655"
    })
    print(result)

# 1. 获取access_token
# 2.一系列的http 请求
# 3. 一旦发现过期，重新获取一次access token
